import { HttpOption, Response, http } from "@/api/http";

// 最大并发请求数量
const MAX_CUR_COUNT = 10;
export default function (httpOptions: HttpOption[], maxReqCount: number = MAX_CUR_COUNT) {
  if (httpOptions.length === 0) {
    return
  }
  let nextIndex = 0; // 下一个请求的选项下标
  let finishCount = 0; // 请求是否结束
  const result: Response<any>[] = []; // 存放请求的结果
  return new Promise(resolve => {
    async function _request() {
      let i = nextIndex;
      nextIndex++;
      const option = httpOptions[nextIndex];
      const resp = await http(option)
      // 如果这里请求失败了，可以添加自定义逻辑
      result[i] = resp;
      // 一个请求完成后，再添加一个请求
      if (nextIndex < httpOptions.length) {
        _request()
      }
      // 每完成一个请求，我们就将finishCount + 1
      finishCount++;
      // 请求结束了
      if (finishCount === httpOptions.length) {
        resolve(result)
      }
    }
    for (let i = 0; i < Math.min(httpOptions.length, maxReqCount); i++) {
      _request()
    }

  })
}